#include "iic_master.h"
#include "driver/i2c.h"
#include <stdio.h>
#include <string.h>
#include <stdlib.h>

#include "freertos/FreeRTOS.h"
#include "freertos/task.h"
#include "freertos/queue.h"

#include "esp_log.h"
#include "esp_system.h"
#include "esp_err.h"

uint8_t bt = 0;
esp_err_t iic_master_gpio_init(void)
{
    int i2c_master_port = I2C_EXAMPLE_MASTER_NUM;
    i2c_config_t conf;
    conf.mode = I2C_MODE_MASTER;
    conf.sda_io_num = I2C_EXAMPLE_MASTER_SDA_IO;
    conf.sda_pullup_en = 0;
    conf.scl_io_num = I2C_EXAMPLE_MASTER_SCL_IO;
    conf.scl_pullup_en = 0;
    ESP_ERROR_CHECK(i2c_driver_install(i2c_master_port, conf.mode));
    ESP_ERROR_CHECK(i2c_param_config(i2c_master_port, &conf));

    return ESP_OK;
}

void faster_iic_start(void)
{
    IIC_SCL_SET();
    IIC_SDA_SET();
    os_delay_us(4);
    IIC_SDA_CLEAR();
    os_delay_us(4);
    IIC_SCL_CLEAR();
}

void faster_iic_stop(void)
{
    IIC_SCL_SET();
    os_delay_us(4);
    IIC_SDA_CLEAR();
    os_delay_us(4);
    IIC_SDA_SET();
}

void faster_iic_wait_ack(void)
{
    IIC_SCL_SET();
    os_delay_us(5);
    IIC_SCL_CLEAR();
}

void faster_iic_write_byte(unsigned char data)
{
    bt = data;

    IIC_SCL_CLEAR();
    IIC_SDA_date((bt >> 7));
    os_delay_us(3);
    IIC_SCL_SET();
    os_delay_us(3);
    IIC_SCL_CLEAR();

    IIC_SCL_CLEAR();
    IIC_SDA_date((bt >> 6) & 0x01);
    os_delay_us(3);
    IIC_SCL_SET();
    os_delay_us(3);
    IIC_SCL_CLEAR();

    IIC_SCL_CLEAR();
    IIC_SDA_date((bt >> 5) & 0x01);
    os_delay_us(3);
    IIC_SCL_SET();
    os_delay_us(3);
    IIC_SCL_CLEAR();

    IIC_SCL_CLEAR();
    IIC_SDA_date((bt >> 4) & 0x01);
    os_delay_us(3);
    IIC_SCL_SET();
    os_delay_us(3);
    IIC_SCL_CLEAR();

    IIC_SCL_CLEAR();
    IIC_SDA_date((bt >> 3) & 0x01);
    os_delay_us(3);
    IIC_SCL_SET();
    os_delay_us(3);
    IIC_SCL_CLEAR();

    IIC_SCL_CLEAR();
    IIC_SDA_date((bt >> 2) & 0x01);
    os_delay_us(3);
    IIC_SCL_SET();
    os_delay_us(3);
    IIC_SCL_CLEAR();

    IIC_SCL_CLEAR();
    IIC_SDA_date((bt >> 1) & 0x01);
    os_delay_us(3);
    IIC_SCL_SET();
    os_delay_us(3);
    IIC_SCL_CLEAR();

    IIC_SCL_CLEAR();
    IIC_SDA_date((bt >> 0) & 0x01);
    os_delay_us(3);
    IIC_SCL_SET();
    os_delay_us(3);
    IIC_SCL_CLEAR();
}

void faster_iic_write_cmd(unsigned char cmd)
{
    faster_iic_start();
    faster_iic_write_byte(0x78); //Slave address,SA0=0
    faster_iic_wait_ack();
    faster_iic_write_byte(0x00); //write command
    faster_iic_wait_ack();
    faster_iic_write_byte(cmd);
    faster_iic_wait_ack();
    faster_iic_stop();
}
